package com.yawn.spock.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.util.ArrayList;
import java.util.List;

/**
 * XPath读取xml，了解更多请搜索 xpath、xsd、xquery等关键词
 * @author yawn
 */
public class XpathReader {

    private Document xml;

    public XpathReader(String filePath) {
        try {
            xml = new SAXReader().read(filePath);
        } catch (DocumentException e) {
            e.printStackTrace();
            xml = null;
            throw new RuntimeException(e.getMessage());
        }
    }

    public List<Node> getNodes(String xpath) {
        if (xml == null) {
            return new ArrayList<>();
        }
        List list = xml.selectNodes(xpath);
        if (list == null || list.size() <= 0) {
            return new ArrayList<>();
        }
        return (List<Node>) list;
    }

    public Node getNode(String xpath) {
        List<Node> nodeList = getNodes(xpath);
        if (nodeList == null || nodeList.size() <= 0) {
            return null;
        }
        return nodeList.get(0);
    }

    public String getText(String xpath) {
        String text = getNode(xpath).getText();
        if (text.trim().equals("")) {
            return null;
        }
        return text;
    }

    public String getString(String xpath) {
        return getNode(xpath).getStringValue();
    }
}
